package compare;


import java.util.Arrays;
import java.util.Comparator;

/*
* 自定义比较器
* 1、自定义比较器类
* 2、比较器类实现Comparator接口
* 3、重写compare（）方法
* 4、调用比较器， Arrays.sort(goods,new Comparator_());
* */
public class Comparator_ implements Comparator {  //实现比较器

    //根据价格进行排序
    @Override
    public int compare(Object o1, Object o2) {  //重写compare
        if(o1 instanceof Goods1 && o2 instanceof Goods1){ //instanceof 判断是不是同一个类
            Goods1 goods1 = (Goods1)o1;
            Goods1 goods2 = (Goods1)o2;
            if (goods1.getPrice()>goods2.getPrice()){
                return 1;
            }else if (goods1.getPrice()<goods2.getPrice()){
                return -1;
            }else { //如果价格相等，按照名字排序
                if (goods1.getName().compareTo(goods2.getName())>0){
                    return 1;
                }else if (goods1.getName().compareTo(goods2.getName())<0){
                    return -1;
                }else {
                    return 0;
                }
            }
        }
        throw new RuntimeException("传入的数据类型不一致");
    }
}
class Goods1 {
    private String name;
    private double price;

    public Goods1() {
    }

    public Goods1(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

}
class testMain{
    public static void main(String[] args) {
        Goods1 [] goods = new Goods1[5];
        goods[0] = new Goods1("a",42.1);
        goods[1] = new Goods1("b",22.1);
        goods[2] = new Goods1("c",52.1);
        goods[3] = new Goods1("d",22.1);
        goods[4] = new Goods1("e",82.1);

        Arrays.sort(goods, new Comparator<Goods1>() {
            @Override
            public int compare(Goods1 o1, Goods1 o2) {
                return 0;
            }
        });

        System.out.println(Arrays.toString(goods));
    }
}
